package com.yugao.fintech.antelope.infra.weixin.mp.handler.wx.user;

import com.yugao.fintech.antelope.infra.weixin.mp.MpContextHolder;
import com.yugao.fintech.antelope.infra.weixin.mp.handler.scanbiz.BaseWxScanEventHandler;
import com.yugao.fintech.antelope.infra.weixin.mp.service.MpAutoReplyService;
import com.yugao.fintech.antelope.infra.weixin.mp.service.MpUserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 关注的事件处理器
 *

 */
@Component
@Slf4j
public class SubscribeHandler implements WxMpMessageHandler {

    @Autowired
    private MpUserService mpUserService;

    @Autowired
    private MpAutoReplyService mpAutoReplyService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context,
                                    WxMpService weixinService, WxSessionManager sessionManager) throws WxErrorException {
        // 第一步，从公众号平台，获取粉丝信息
        log.info("粉丝 [{}] 关注", wxMessage.getFromUser());
        WxMpUser wxMpUser = null;
        try {
            wxMpUser = weixinService.getUserService().userInfo(wxMessage.getFromUser());
        } catch (WxErrorException e) {
            log.error("粉丝 [{}] 获取粉丝信息失败！", wxMessage.getFromUser(), e);
        }

        // 第二步，保存粉丝信息
        String appId = MpContextHolder.getParam().getAppId();
        mpUserService.saveUser(appId, wxMpUser);

        // 关注可能是通过扫码进入的, 所以这里要判断并处理一下
        BaseWxScanEventHandler.handle(wxMessage, wxMessage.getEventKey().replace("qrscene_", ""));

        // 第三步，回复关注的欢迎语
        return mpAutoReplyService.replyForSubscribe(appId, wxMessage);
    }

}
